package top.soning.disk.service.impl;

import org.apache.ibatis.javassist.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;
import top.soning.disk.entity.FileEntity;
import top.soning.disk.mapper.FileMapper;
import top.soning.disk.service.FileUploadService;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    FileMapper fileMapper;

    private String savePath = "src/main/resources/assets/";

    @Override
    public FileEntity start(MultipartFile file) {
        try {
//            1. 保存到磁盘
            File dest = new File(this.savePath + file.getOriginalFilename());
            this.saveSingleFile(file);
//            2. 保存到数据库
            FileEntity fileEntity = this.getFileInfo(dest);
            int affect = this.addFileRecordToDB(fileEntity);
//            3. 返回保存的文件信息
            if (affect == 1) {
                return fileEntity;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 存储上传的文件到指定目录下
     *
     * @param file 上传的文件对象 MultipartFile
     * @throws NotFoundException,IOException
     */
    @Override
    public void saveSingleFile(MultipartFile file) throws NotFoundException, IOException {
        if (file.isEmpty()) {
            throw new NotFoundException("File Not Found");
        }
        /***************   存储文件   ***************/
        File dest = new File(this.savePath + file.getOriginalFilename());
        file.transferTo(new File(dest.getAbsolutePath()));
    }

    /**
     * 将以存储的文件的信息写入数据库中
     *
     * @param fileEntity 文件对象 包含其简单信息
     * @return int 影响的行数
     */
    @Override
    public int addFileRecordToDB(FileEntity fileEntity) {
        return fileMapper.insertFile(fileEntity);
    }

    /**
     * 获取符合FileEntity对象的文件信息
     *
     * @param file 上传的文件对象 File
     * @return FileEntity
     * @throws IOException
     */
    public FileEntity getFileInfo(File file) throws IOException {
        FileEntity fileEntity = new FileEntity();
        fileEntity.setMd5(this.getFileMd5(file));
        fileEntity.setCreateTime(new Date().getTime());
        fileEntity.setSize(file.length());
        return fileEntity;
    }

    /**
     * 计算文件MD5
     *
     * @param file a file object
     * @return md5 file's md5 String  String
     */
    public String getFileMd5(File file) throws IOException {
        return DigestUtils.md5DigestAsHex(new FileInputStream(file));
    }
}
